package com.lzw.skinchange.androidx.appcompat.widget;

import android.content.res.TypedArray;
import androidx.core.widget.CompoundButtonCompat;
import android.util.AttributeSet;
import android.widget.CompoundButton;

import com.lzw.skinchange.androidx.appcompat.content.SkinCompatVectorResources;
import com.lzw.skinchange.androidx.core.content.SkinCompatResources;
import com.lzw.skinchange.androidx.core.widget.SkinCompatHelper;


public class SkinCompatCompoundButtonHelper extends SkinCompatHelper {
    private final CompoundButton mView;
    private int mButtonResourceId = SkinCompatHelper.INVALID_ID;
    private int mButtonTintResId = SkinCompatHelper.INVALID_ID;

    public SkinCompatCompoundButtonHelper(CompoundButton view) {
        mView = view;
    }

    void loadFromAttributes(AttributeSet attrs, int defStyleAttr) {
        TypedArray a = mView.getContext().obtainStyledAttributes(attrs, androidx.appcompat.R.styleable.CompoundButton,
                defStyleAttr, SkinCompatHelper.INVALID_ID);
        try {
            if (a.hasValue(androidx.appcompat.R.styleable.CompoundButton_android_button)) {
                mButtonResourceId = a.getResourceId(
                        androidx.appcompat.R.styleable.CompoundButton_android_button, SkinCompatHelper.INVALID_ID);
            }

            if (a.hasValue(androidx.appcompat.R.styleable.CompoundButton_buttonTint)) {
                mButtonTintResId = a.getResourceId(androidx.appcompat.R.styleable.CompoundButton_buttonTint, SkinCompatHelper.INVALID_ID);
            }
        } finally {
            a.recycle();
        }
        applySkin();
    }

    public void setButtonDrawable(int resId) {
        mButtonResourceId = resId;
        applySkin();
    }

    @Override
    public void applySkin() {
        mButtonResourceId = SkinCompatHelper.checkResourceId(mButtonResourceId);
        if (mButtonResourceId != SkinCompatHelper.INVALID_ID) {
            mView.setButtonDrawable(SkinCompatVectorResources.getDrawableCompat(mView.getContext(), mButtonResourceId));
        }
        mButtonTintResId = SkinCompatHelper.checkResourceId(mButtonTintResId);
        if (mButtonTintResId != SkinCompatHelper.INVALID_ID) {
            CompoundButtonCompat.setButtonTintList(mView, SkinCompatResources.getColorStateList(mView.getContext(), mButtonTintResId));
        }
    }
}
